package com.lsh.airticket.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;

/**
 * @author lsh
 * @date 2021/2/13
 **/
public class JWTUtil {
    private static final long EXPIRE_TIME = 7*24*60*1000; //设置过期时间
    private static final String TOKEN_SECRET = "token123";  //密钥盐
    private static final Algorithm ALGORITHM =  Algorithm.HMAC256(TOKEN_SECRET); //设置加密算法

    /**
     * 生成token
     * @param map
     * @return
     */
    public static String create(HashMap<String, Object> map) {
        String token = JWT.create()
                .withClaim("user", map)
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRE_TIME))
                .sign(ALGORITHM);

        return token;
    }

    /**
     * 验证 token是否合法
     * @param token
     */
    public static DecodedJWT verify(String token) {
        return JWT.require(ALGORITHM).build().verify(token);
    }

    /**
     * 获取载荷的值
     */
    public static HashMap<String, Object> getClaim(String token) {
        return (HashMap<String, Object>) verify(token).getClaim("user").asMap();
    }


}
